package com.appspot.moviesessions.interfaces.webapp;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.appspot.moviesessions.infrastructure.scraper.Scraper;
import com.appspot.moviesessions.model.SessionRepository;

@Controller
@RequestMapping("/update/*")
public class ScrapeController {

	private Scraper movieInformationScraper;
	private Scraper sessionScraper;
	private SessionRepository repository;

	@Autowired
	public ScrapeController(
	        @Qualifier("movieInformationScraper") Scraper movieInformationScraper,
	        @Qualifier("sessionScraper") Scraper sessionScraper,
	        SessionRepository repository) {
		this.movieInformationScraper = movieInformationScraper;
		this.sessionScraper = sessionScraper;
		this.repository = repository;
	}

	@RequestMapping("movie")
	public String updateMovieInformation(
	        @RequestParam(value = "name", required = true) String movieName) {
		Map<String, String> parameters = new HashMap<String, String>();
		parameters.put("movie", movieName);
		movieInformationScraper.scrape(parameters);
		return "ok";
	}

	@RequestMapping(value = "/session", method = RequestMethod.GET)
	public String updateSessions() {
		repository.purge();
		sessionScraper.scrape(Collections.EMPTY_MAP);
		return "ok";
	}

	@RequestMapping(value = "/purge", method = RequestMethod.GET)
	public String purge() {
		repository.purge();
		return "ok";
	}

}
